package com.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.model.Student;
import com.model.Teacher;
import com.model.User;
import com.util.MD5;
import com.util.validator.LoginValidator;

/**
 * Created by chaiyuan on 2017/5/3.
 */
public class IndexController extends Controller {
  public void index(){
    render("/LoginPage.jsp");
  }
  @Before(LoginValidator.class)
  public void login(){
    int role = getParaToInt("role");
    String no = getPara("no");
    String password = getPara("password");
    String pass_md5 = new MD5().toMD5(password);
    switch (role){
      case 1:
        User user = User.dao.findFirst("select *  from user where name = "+no);
        if(user.getStr("password").equals(pass_md5)) {
            setSessionAttr("user",user);
            redirect("/admin");
        }
        break;
      case  2:
        Teacher teacher = Teacher.dao.findFirst("select * from teacher where name = "+no);
        if(teacher.getStr("password").equals(pass_md5)) {
            setSessionAttr("user",teacher);
            redirect("/teacher");
        }
        break;
      case  3:
        Student student = Student.dao.findFirst("select * from student where name ="+no);
        if(student.getStr("password").equals(pass_md5)) {
            setSessionAttr("user",student);
            redirect("/student");
        }
        break;
      default:
        break;
    }
  }
  @ActionKey("/logout")
  public void logout(){
    setSessionAttr("user",null);
    redirect("/index");
  }
  @ActionKey("/modify")
  public void modify(){
        if(getSessionAttr("user") instanceof Teacher){
            Teacher.dao.findById(((Teacher) getSessionAttr("user")).getInt("tea_id")).set("name",getPara("username")).set("password",new MD5().toMD5(getPara("password"))).update();
        }else if(getSessionAttr("user") instanceof Student){
            Student.dao.findById(((Student) getSessionAttr("user")).getInt("stu_id")).set("name",getPara("username")).set("password",new MD5().toMD5(getPara("password"))).update();
        }else if(getSessionAttr("user") instanceof Teacher){
            User.dao.findById(((User) getSessionAttr("user")).getInt("id")).set("name",getPara("username")).set("password",new MD5().toMD5(getPara("password"))).update();
        }
  }
}
